<template>
  <div class="params">
    <div class="params_header">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>分类参数</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <el-card shadow="hover" class="params_con">
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon :closable='false'>
      </el-alert>

      <!-- 三级联表 -->
      <div class="block">
        <span class="demonstration">选择商品分类：</span>
        <el-cascader v-model="treeValue" :options="catelist" @change="handleChange"
          :props="cateProps" clearable></el-cascader>
      </div>

      <!--  -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <!-- 动态参数面板 -->
          <el-button type="primary" :disabled="buttonAbled" @click="add">添加参数</el-button>
          <el-table :data="manytable" style="width: 100%">
            <!-- 展开行 -->
            <el-table-column type="expand">
              // eslint-disable-next-line vue/no-unused-vars
              <template slot-scope="props">
                <el-form label-position="left" inline class="demo-table-expand">
                  <el-form-item>
                    <!-- 小标签 -->
                    <el-tag class="expand" closable v-for="(item,i) in  props.row.attr_vals "
                      :key="i" :disable-transitions="false"
                      @close="handleCloseSmall(props.row.attr_vals,item)">
                      {{ item }}</el-tag>
                    <!-- 添加标签 -->
                    <el-input class="input-new-tag" v-if="props.row.inputVisible"
                      v-model="props.row.inputValue" ref="saveTagInput" size="small"
                      @keyup.enter.native="handleInputConfirm(props.row,props.row.attr_vals)"
                      @blur="handleInputConfirm(props.row,props.row.attr_vals)">
                    </el-input>
                    <!-- 添加标签按钮 -->
                    <el-button v-else class="button-new-tag" size="small"
                      @click="showInput(props.row)">+ New
                      Tag</el-button>
                  </el-form-item>
                </el-form>
              </template>
            </el-table-column>
            <el-table-column label="#" type="index" width="200">
            </el-table-column>
            <el-table-column label="参数名称" prop="attr_name">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit"
                  @click="handleEditMany(scope.$index, scope.row)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete"
                  @click="handleDeleteMany(scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <!-- 静态属性面板 -->
          <el-button type="primary" :disabled="buttonAbled" @click="add">添加属性</el-button>
          <el-table :data="onlytable" style="width: 100%">
            <el-table-column type="expand">
              // eslint-disable-next-line vue/no-unused-vars
              <template slot-scope="props">
                <el-form label-position="left" inline class="demo-table-expand">
                  <el-form-item>
                    <!-- 小标签 -->
                    <el-tag class="expand" closable v-for="(item,i) in  props.row.attr_vals "
                      :key="i" :disable-transitions="false"
                      @close="handleCloseSmall(item,props.row)">
                      {{ item }}</el-tag>
                    <!-- 添加标签 -->
                    <el-input class="input-new-tag" v-if="props.row.inputVisible"
                      v-model="props.row.inputValue" ref="saveTagInput" size="small"
                      @keyup.enter.native="handleInputConfirm(props.row,props.row.attr_vals)"
                      @blur="handleInputConfirm(props.row,props.row.attr_vals)">
                    </el-input>
                    <!-- 添加标签按钮 -->
                    <el-button v-else class="button-new-tag" size="small"
                      @click="showInput(props.row)">+ New
                      Tag</el-button>
                  </el-form-item>
                </el-form>
              </template>
            </el-table-column>
            <el-table-column label="#" type="index" width="200">
            </el-table-column>
            <el-table-column label="参数名称" prop="attr_name">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit"
                  @click="handleEditMany(scope.$index, scope.row)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete"
                  @click="handleDeleteMany(scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 添加框 -->
        <el-dialog :title='`添加${getnamed}`' :visible.sync="dialogAddFormVisible"
          :before-close="handleClose" @close="addcancel">
          <el-form label-width="100px" ref="addDialog">
            <el-form-item :label=" getnamed">
              <el-input v-model="addresult" autocomplete="off"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogAddFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="confirmAdd">确 定</el-button>
          </div>
        </el-dialog>

        <!-- 编辑框 -->
        <el-dialog :title='`修改${getnamed}`' :visible.sync="dialogEditorFormVisible"
          :before-close="handleClose" @close="Editorcancel">
          <el-form label-width="100px" ref="addDialog">
            <el-form-item :label=" getnamed">
              <el-input v-model="EditorResult" autocomplete="off"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogEditorFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="confirmEditor">确 定</el-button>
          </div>
        </el-dialog>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'paRams',
  data() {
    return {
      // 三级联表列表
      catelist: [],
      // 三级联表列表结果
      treeValue: [],
      // 三级联表格式
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },
      // Tab标签页默认
      activeName: 'many',
      // 按钮是否禁用
      buttonAbled: true,
      // 动态参数表
      manytable: [],
      // 静态参数表
      onlytable: [],
      // 添加框的显示
      dialogAddFormVisible: false,
      // 添加框校验
      addRules: {
        addName: [
          { required: true, message: '请正确输入添加名称', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' },
        ],
      },
      // 添加框结果
      addresult: '',
      // 编辑框的显示
      dialogEditorFormVisible: false,
      // 编辑框需要的属性id
      EditorID: 0,
      // 编辑框结果
      EditorResult: '',
      // 添加小标签的显示
      inputVisible: false,
      // 小标签数组
      smallArr: [],
      // 添加的小标签结果
      inputValue: '',
    }
  },
  computed: {
    // 计算添加框名
    getnamed() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    },
    // 计算小属性遇逗号分离
    // getLeave() {
    //   return (val) => {
    //     this.smallArr = val.split(',')
    //     return this.smallArr
    //   }
    // },
  },
  methods: {
    async getcateList() {
      const { data: getcateListres } = await this.$http.get('categories')
      // console.log(getcateListres)
      this.catelist = getcateListres.data
    },
    // 三级联表选择结果
    handleChange() {
      if (this.treeValue.length != 3) {
        this.treeValue = []
        this.$message.error('抱歉，请选择三级列表')
        this.manytable = []
        this.onlytable = []
        return
      }
      this.buttonAbled = false
      this.manyOnlyinfo()
    },
    // 获取动、静态数据
    async manyOnlyinfo() {
      const attrID = this.treeValue[2]
      const { data: handleChangeres } = await this.$http.get(`categories/${attrID}/attributes`, {
        params: { sel: this.activeName },
      })
      if (handleChangeres.meta.status != 200) {
        this.$message.error('抱歉，获取失败')
        return
      }
      console.log(handleChangeres)
      this.$message.success('获取成功')

      handleChangeres.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        // 赋给每行的添加小标签按钮一个不同的显示值与model值
        item.inputVisible = false
        item.inputValue = ''
      })

      if (this.activeName === 'many') {
        this.manytable = handleChangeres.data
      } else if (this.activeName === 'only') {
        this.onlytable = handleChangeres.data
      }
    },
    // Tab标签页切换
    handleClick() {
      if (this.treeValue.length == 3) {
        this.manyOnlyinfo()
      }
    },
    // 添加框
    add() {
      this.dialogAddFormVisible = true
    },
    // 关闭添加框前提示
    handleClose(done) {
      this.$confirm('确认关闭?填写数据将不被保存')
        .then(() => {
          done()
        })
        .catch(() => {})
    },
    // 关闭添加框
    addcancel() {
      this.addresult = ''
    },
    // 确定添加
    async confirmAdd() {
      const attrID = this.treeValue[2]
      const { data: resAdd } = await this.$http.post(`categories/${attrID}/attributes`, {
        attr_name: this.addresult,
        attr_sel: this.activeName,
      })
      if (resAdd.meta.status != 201) {
        this.$message.error('抱歉，添加失败')
        return
      }
      this.$message.success('添加成功')
      this.manyOnlyinfo()
      this.dialogAddFormVisible = false
    },
    // 点击编辑按钮
    handleEditMany(a, b) {
      this.dialogEditorFormVisible = true
      this.EditorID = b.attr_id
    },
    // 关闭编辑框
    Editorcancel() {
      this.EditorResult = ''
    },
    // 确定编辑
    async confirmEditor() {
      const attrID = this.treeValue[2]
      const { data: resEditor } = await this.$http.put(
        `categories/${attrID}/attributes/${this.EditorID}`,
        {
          attr_name: this.EditorResult,
          attr_sel: this.activeName,
        }
      )
      if (resEditor.meta.status != 200) {
        this.$message.error('抱歉，修改失败')
        return
      }
      this.$message.success('修改成功')
      this.manyOnlyinfo()
      this.dialogEditorFormVisible = false
    },
    // 点击删除
    handleDeleteMany(a, b) {
      this.$confirm('此操作将永久删除此分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const attrID = this.treeValue[2]
          const { data: deleteres } = await this.$http.delete(
            `categories/${attrID}/attributes/${b.attr_id}`
          )
          if (deleteres.meta.status != 200) {
            this.$message.error('删除失败，请重试')
          }
          this.$message.success('删除成功')
          this.manyOnlyinfo()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    // 小标签点击删除
    async handleCloseSmall(item, row) {
      row.attr_vals.splice(row.attr_vals.indexOf(item), 1)
      const attrID = this.treeValue[2]
      const { data: resEditorSmall } = await this.$http.put(
        `categories/${attrID}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: this.activeName,
          attr_vals: row.attr_vals.join(),
        }
      )
      if (resEditorSmall.meta.status != 200) {
        this.$message.error('抱歉，修改失败')
        return
      }
      console.log(resEditorSmall)
      this.$message.success('修改成功')
    },
    // 点击按钮显示出添加小标签
    showInput(items) {
      items.inputVisible = true
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 小标签添加
    async handleInputConfirm(item, items) {
      let inputValue = item.inputValue
      if (inputValue) {
        items.push(inputValue)
      }
      const attrID = this.treeValue[2]
      const { data: resEditorSmall } = await this.$http.put(
        `categories/${attrID}/attributes/${item.attr_id}`,
        {
          attr_name: item.attr_name,
          attr_sel: this.activeName,
          attr_vals: items.join(),
        }
      )
      if (resEditorSmall.meta.status != 200) {
        this.$message.error('抱歉，修改失败')
        return
      }
      console.log(resEditorSmall)
      this.$message.success('修改成功')
      item.inputVisible = false
      item.inputValue = ''
    },
  },
  created() {
    this.getcateList()
  },
}
</script>

<style lang='less' scoped>
.params {
  height: 100%;
}
.params_header {
  .el-breadcrumb-item {
    font-size: 17px;
  }
}
.params_con {
  margin-top: 30px;
  background: #fff;
  padding: 20px 20px;
  .el-table {
    margin-top: 20px;
  }
}
.block {
  margin: 15px 0;
}
.el-cascader {
  width: 500px;
}
.el-tab-pane > .el-button {
  margin: 20px 0;
}
.expand {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>